package pl.edu.agh.mr.nb.server;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Topic;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

import pl.edu.agh.mr.nb.node.ComputationResultMsg;

public class Client {

	public static final int DIMX = 600;
	public static final int DIMY = 600;
	
	public String clientName;
	public int clientStatus; 
	public TopicPublisher publisher;
	public TopicSession session;
	public Topic topic;
	public int divideRatio;
	private int count;
	public ComputationResultMsg finalResults;
	
	public Client(String clientName, TopicSession session, String topicPrefix, int divideRatio) throws JMSException {
	
		System.out.println("Registering client: "+clientName);
		this.clientName = clientName;
		this.clientStatus = ClientStatus.WAITING;
		this.session = session;
		this.topic = session.createTopic(topicPrefix+"/"+clientName);
		this.publisher = session.createPublisher(this.topic);
		this.divideRatio = divideRatio;
		this.finalResults = new ComputationResultMsg();
		this.count = 0;
	}


	public void sendResultsToClient() throws JMSException {
		System.out.println("Sending back results to the client: "+clientName);
		ObjectMessage message = session.createObjectMessage();
    	message.setObject(finalResults);
    	publisher.publish(message);
    	count = 0;
	}


	public void appendPartlyResults(ComputationResultMsg result) {
		int [] fullResult = finalResults.results;
		int [] partialResult = result.results;
		
		System.err.println("appending part " + result.id);
		
		int startPoint = result.id * DIMX*(DIMY/divideRatio);
		System.arraycopy(partialResult, 0, fullResult, startPoint, result.size);
		
		count++;
	}


	// it tells whether the whole result message has been assembled
	public boolean readyToSendBack() {	
		if (count == divideRatio)
			return true;
		else 
			return false;
	}
}

